package com.anjie.powerproject.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.anjie.powerproject.common.Result;
import com.anjie.powerproject.entity.Point;
import com.anjie.powerproject.entity.TaskConfig;
import com.anjie.powerproject.pojo.dto.TaskConfigDTO;
import com.anjie.powerproject.pojo.dto.TaskConfigDTOList;
import com.anjie.powerproject.service.PointService;
import com.anjie.powerproject.service.TaskConfigService;
import com.anjie.powerproject.util.ExcelUtil;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * 点位配置Controller
 */
@Controller
@RequestMapping("taskConfig")
public class TaskConfigController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    TaskConfigService taskConfigService;
    @Autowired
    PointService pointService;

    @RequestMapping(value = "/getAll")
    @ResponseBody
    public Result getAll(){
        List<TaskConfig> taskConfigList=taskConfigService.getTaskConfigList();
        //Map<String, List<String>> prodMap = taskConfigList.stream().collect(Collectors.groupingBy(TaskConfig::getDevCode, Collectors.mapping(TaskConfig::getIntervalType, Collectors.toList())));
        //TaskConfigMap中key是pointId，value是pointId对应的List<TaskConfig>>
        Map<Integer, List<TaskConfig>> TaskConfigMap= taskConfigList.stream().collect(Collectors.groupingBy(TaskConfig::getPointId));

        List<TaskConfigDTO> taskConfigDTOS=new ArrayList<>();

        List<Point> pointList=pointService.getPointList();
        for (Point point:pointList) {
            if(TaskConfigMap.containsKey(point.getId())){ //存在，拼接数据
                List<TaskConfig> list=TaskConfigMap.get(point.getId());
                TaskConfigDTO taskConfigDTO=new TaskConfigDTO();
                taskConfigDTO.setPointId(point.getId());
                taskConfigDTO.setName(point.getPointName());
                taskConfigDTO.setId(point.getId());
                List<String> intervalTypeDownloadList=new ArrayList<>();
                List<String> intervalTypeUploadList=new ArrayList<>();

                list.forEach(taskConfig -> {
                    if(taskConfig.getTaskType()!=null&&taskConfig.getTaskType()==0){  //下载
                        intervalTypeDownloadList.add(String.valueOf(taskConfig.getIntervalType()));
                    }else{ //上传
                        intervalTypeUploadList.add(String.valueOf(taskConfig.getIntervalType()));
                    }
                });

                taskConfigDTO.setIntervalTypeDownloadList(intervalTypeDownloadList);
                taskConfigDTO.setIntervalTypeUploadList(intervalTypeUploadList);
                taskConfigDTO.setStatisticType(list.get(0).getStatisticType());
                taskConfigDTO.setDevCode(list.get(0).getDevCode());
                taskConfigDTO.setSourceType(String.valueOf(list.get(0).getGetType()));

                taskConfigDTOS.add(taskConfigDTO);

            }else{//不存在，即点位还没有配置过 返回空的taskConfigDTO
                TaskConfigDTO taskConfigDTO=new TaskConfigDTO();
                taskConfigDTO.setPointId(point.getId());
                taskConfigDTO.setDevCode(point.getDevCode());
                taskConfigDTO.setName(point.getPointName());
                taskConfigDTO.setId(point.getId());
                List<String> intervalTypeDownloadList=new ArrayList<>();
                List<String> intervalTypeUploadList=new ArrayList<>();
                taskConfigDTO.setIntervalTypeDownloadList(intervalTypeDownloadList);
                taskConfigDTO.setIntervalTypeUploadList(intervalTypeUploadList);

                taskConfigDTOS.add(taskConfigDTO);
            }
        }

//        System.out.println(taskConfigDTOS.toString());
        //按point_id升序排列
        List<TaskConfigDTO> sortedTaskConfigDTOS = taskConfigDTOS
                .stream()
                .sorted( (p, p2) -> (p.getPointId() - p2.getPointId()) )
                .collect( toList() );
        return new Result(sortedTaskConfigDTOS,true,1,"查询成功");
    }



//    @RequestMapping(value = "/getAll")
//    @ResponseBody
//    public Result getAll(){
//        List<TaskConfig> taskConfigList=taskConfigService.getTaskConfigList();
////        Map<String, List<String>> prodMap = taskConfigList.stream().collect(Collectors.groupingBy(TaskConfig::getDevCode, Collectors.mapping(TaskConfig::getIntervalType, Collectors.toList())));
//
//        //TaskConfigMap中key是devCode，value是devCode对应的List<TaskConfig>>
//        Map<String, List<TaskConfig>> TaskConfigMap= taskConfigList.stream().collect(Collectors.groupingBy(TaskConfig::getDevCode));
//
//        List<TaskConfigDTO> taskConfigDTOS=new ArrayList<>();
//        TaskConfigMap.forEach((k, v) -> {
//            TaskConfigDTO taskConfigDTO=new TaskConfigDTO();
//            taskConfigDTO.setDevCode(k);
//
//            List<String> intervalTypeDownloadList=new ArrayList<>();
//            List<String> intervalTypeUploadList=new ArrayList<>();
//            List<TaskConfig> list=v;
//            list.forEach(taskConfig -> {
//                if(taskConfig.getTaskType()!=null&&taskConfig.getTaskType()==0){  //下载
//                    intervalTypeDownloadList.add(String.valueOf(taskConfig.getIntervalType()));
//                }else{ //上传
//                    intervalTypeUploadList.add(String.valueOf(taskConfig.getIntervalType()));
//                }
//            });
//
//            taskConfigDTO.setIntervalTypeDownloadList(intervalTypeDownloadList);
//            taskConfigDTO.setIntervalTypeUploadList(intervalTypeUploadList);
//            taskConfigDTO.setStatisticType(list.get(0).getStatisticType());
//            taskConfigDTO.setPointId(list.get(0).getPointId());
//
//            Point point = pointService.getPointByDevCode(k);
//            if(point!=null) {
//                taskConfigDTO.setName(point.getPointName());
//                taskConfigDTO.setId(point.getId());
//            }else {
//                taskConfigDTO.setName("该点位不存在");
//                taskConfigDTO.setId(0);
//            }
//            taskConfigDTOS.add(taskConfigDTO);
//        });
////        System.out.println(taskConfigDTOS.toString());
//        //按point_id升序排列
//        List<TaskConfigDTO> sortedTaskConfigDTOS = taskConfigDTOS
//                .stream()
//                .sorted( (p, p2) -> (p.getPointId() - p2.getPointId()) )
//                .collect( toList() );
//        return new Result(sortedTaskConfigDTOS,true,1,"查询成功");
//    }


    @RequestMapping(value = "/update")
    @ResponseBody
    public Result update(@RequestBody TaskConfigDTOList taskConfigDTOList){
        List<TaskConfigDTO> taskConfigDTOS=taskConfigDTOList.getTaskConfigDTOS();
//        System.out.println(taskConfigDTOS.toString());
        Date date = new Date();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String curTime=sdf.format(date);

        for (TaskConfigDTO taskConfigDTO:taskConfigDTOS) {
            String devCode=taskConfigDTO.getDevCode();
            List<TaskConfig> taskConfigList=taskConfigService.getByPointId(taskConfigDTO.getPointId());

            List<TaskConfig> newTaskConfigList=new ArrayList<>();
            for(int i=0;i<taskConfigDTO.getIntervalTypeDownloadList().size();i++){
//                System.out.println("++++0"+taskConfigDTO.getIntervalTypeDownloadList().get(i));
                if(!taskConfigDTO.getIntervalTypeDownloadList().get(i).equals("null")) {
                    TaskConfig taskConfig = new TaskConfig(devCode, Integer.valueOf(taskConfigDTO.getIntervalTypeDownloadList().get(i)), taskConfigDTO.getStatisticType(), Integer.valueOf(0), curTime);
                    taskConfig.setPointId(taskConfigDTO.getPointId());
                    //设置interval_num默认值 1，get_type默认值 2
                    taskConfig.setIntervalNum(1);
                    if(taskConfigDTO.getSourceType()!=null)
                        taskConfig.setGetType(Integer.valueOf(taskConfigDTO.getSourceType()));
                    else taskConfig.setGetType(2);
                    newTaskConfigList.add(taskConfig);
                }else continue;
            }

            for(int i=0;i<taskConfigDTO.getIntervalTypeUploadList().size();i++){
                if(!taskConfigDTO.getIntervalTypeUploadList().get(i).equals("null")){
                    TaskConfig taskConfig=new TaskConfig(devCode,Integer.valueOf(taskConfigDTO.getIntervalTypeUploadList().get(i)),taskConfigDTO.getStatisticType(),Integer.valueOf(1),curTime);
                    taskConfig.setPointId(taskConfigDTO.getPointId());
                    //设置interval_num默认值 1，get_type默认值 2
                    taskConfig.setIntervalNum(1);
                    if(taskConfigDTO.getSourceType()!=null)
                        taskConfig.setGetType(Integer.valueOf(taskConfigDTO.getSourceType()));
                    else taskConfig.setGetType(2);
                    newTaskConfigList.add(taskConfig);
                }else continue;
            }

            Integer oldTaskConfigListSize=taskConfigList.size();
            Integer newTaskConfigListSize=newTaskConfigList.size();
            if(oldTaskConfigListSize<=newTaskConfigListSize){
                // 情况一：oldTaskConfigListSize小于newTaskConfigListSize，将数据库中旧的taskConfig更新并且插入新的taskConfig
                //情况二：等于，将数据库中旧的taskConfig更新即可
                for(int i=0;i<oldTaskConfigListSize;i++){
                    newTaskConfigList.get(i).setId(taskConfigList.get(i).getId());
                }
                taskConfigService.saveAll(newTaskConfigList);
            }else{
                //情况三：大于，将多余的旧taskConfig删除，剩下的更新
                for(int i=0;i<newTaskConfigListSize;i++){
                    newTaskConfigList.get(i).setId(taskConfigList.get(i).getId());
                }
                for(int i=newTaskConfigListSize;i<oldTaskConfigListSize;i++){
                    taskConfigService.deleteByTaskConfigId(taskConfigList.get(i).getId());
                }
                taskConfigService.saveAll(newTaskConfigList);
            }
        }

        return new Result(null,true,1,"更新成功");
    }


//    @RequestMapping(value = "/update")
//    @ResponseBody
//    public Result update(@RequestBody TaskConfigDTOList taskConfigDTOList){
//        List<TaskConfigDTO> taskConfigDTOS=taskConfigDTOList.getTaskConfigDTOS();
////        System.out.println(taskConfigDTOS.toString());
//        Date date = new Date();
//        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
//        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
//        String curTime=sdf.format(date);
//
//        for (TaskConfigDTO taskConfigDTO:taskConfigDTOS) {
//            /**
//             * flag标志getIntervalTypeDownloadList和getIntervalTypeUploadList是否有数据，如果没数据会导致taskConfig整条数据丢失
//             * 如果点位没有配置，要有一条空的taskConfig数据
//             */
//            int flag=0;
//
//            String devCode=taskConfigDTO.getDevCode();
//            Integer pointId=taskConfigDTO.getPointId();
//            taskConfigService.deleteByDevCode(devCode);
//            for(int i=0;i<taskConfigDTO.getIntervalTypeDownloadList().size();i++){
////                System.out.println("++++0"+taskConfigDTO.getIntervalTypeDownloadList().get(i));
//                if(!taskConfigDTO.getIntervalTypeDownloadList().get(i).equals("null")) {
//                    flag=1;
//                    TaskConfig taskConfig = new TaskConfig(devCode, Integer.valueOf(taskConfigDTO.getIntervalTypeDownloadList().get(i)), taskConfigDTO.getStatisticType(), Integer.valueOf(0), curTime);
//                    taskConfig.setPointId(taskConfigDTO.getPointId());
//                    //设置interval_num默认值 1，get_type默认值 2
//                    taskConfig.setIntervalNum(1);
//                    taskConfig.setGetType(2);
//                    taskConfigService.saveAndFlush(taskConfig);
//                }else continue;
//            }
//            for(int i=0;i<taskConfigDTO.getIntervalTypeUploadList().size();i++){
//                if(!taskConfigDTO.getIntervalTypeUploadList().get(i).equals("null")){
//                    flag=1;
//                    TaskConfig taskConfig=new TaskConfig(devCode,Integer.valueOf(taskConfigDTO.getIntervalTypeUploadList().get(i)),taskConfigDTO.getStatisticType(),Integer.valueOf(1),curTime);
//                    taskConfig.setPointId(taskConfigDTO.getPointId());
//                    //设置interval_num默认值 1，get_type默认值 2
//                    taskConfig.setIntervalNum(1);
//                    taskConfig.setGetType(2);
//                    taskConfigService.saveAndFlush(taskConfig);
//                }else continue;
//            }
//
//            if(flag==0){
////                System.out.println("插入空白");
//                TaskConfig taskConfig=new TaskConfig();
//                taskConfig.setUpdateTime(curTime);
//                taskConfig.setDevCode(devCode);
//                taskConfig.setPointId(taskConfigDTO.getPointId());
//                if(taskConfigDTO.getStatisticType()!=null)
//                    taskConfig.setStatisticType(taskConfigDTO.getStatisticType());
//                taskConfigService.saveAndFlush(taskConfig);
//            }
//        }
//
//        return new Result(null,true,1,"更新成功");
//    }

    @RequestMapping(value = "/delete")
    @ResponseBody
    public Result delete(@RequestParam("devCodeList")String devCodeList) {
        List<String> devCodes= JSON.parseArray(devCodeList,String.class);
        for(String devCode:devCodes){
            taskConfigService.deleteByDevCode(devCode);
        }

        return new Result(null,true,1,"删除成功");
    }




    //TODO：适配 TaskConfig类
    /**
     * 接收Excel文件，批量导入TaskConfig
     * 复制批量导入point代码，还没有修改成 导入TaskConfig
     * @param pointFile
     * @return
     */
    @RequestMapping(value = "/batchAdd",method = RequestMethod.POST)
    @ResponseBody
    public Result batchAddPoint(@RequestParam("pointFile") MultipartFile pointFile) {
//        System.out.println("上传文件成功-------------------------");
//        System.out.println(pointFile.getOriginalFilename());
//         保存文件并取得文件路径
//        String path = (String)fileService.upload(file).getContent();
//      读取Excel数据
        List<List<String>> lists = ExcelUtil.readExcel(pointFile);
//        System.out.println(lists.size());
//        System.out.println(lists.get(1).size());
//        System.out.println(lists.get(1).get(2));
//        System.out.println("\n\n\n\n\n");
//        System.out.println(lists.get(0)+lists.get(1)+lists.get(2));
//        System.out.println("\n\n\n\n\n");

        //将数据读出,存入数据库
        List<Point> pointList=new ArrayList<>();
        for (int i=1;i<lists.size();i++){
            Point point=new Point();
            point.setDevCode(lists.get(i).get(0));
            point.setPointName(lists.get(i).get(1));
            pointList.add(point);
        }
        String sql = "INSERT INTO point (dev_code, point_name, access ) VALUES (?,?,?)";
//        System.out.println(pointList);
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                String devCode = pointList.get(i).getDevCode();
                String pointName = pointList.get(i).getPointName();
                ps.setString(1, devCode);
                ps.setString(2, pointName);
            }
            public int getBatchSize() {
                return pointList.size();
            }
        });


        return new Result(null,true,1,"添加成功");
    }


    /**
     * 从数据库中获取所有的 taskConfig数据，并写入excel，传输给前端
     * 复制批量导出point代码，还没有修改成 导出TaskConfig
     * @param response
     * @param request
     */
    @RequestMapping(value = "/excel/exportPointInfo",method = RequestMethod.GET)
    public void ExportBankCkeckInfo(HttpServletResponse response, HttpServletRequest request){
        //这里是打印的时间间隔。可忽略
//        String start=request.getParameter("start");
//        String end=request.getParameter("end");
//        System.out.println("打印的起始日期为："+start+"，打印的结束日期为："+end);
        //得到所有要导出的数据
        List<TaskConfig> pointlist = taskConfigService.getTaskConfigList();
        //定义导出的excel名字
        String excelName = "任务配置信息数据表";

        //TODO:适配任务配置信息数据表
        //获取需要转出的excel表头的map字段   前面放实体类的字段名，后面是excel表的列名
        LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
        fieldMap.put("id","ID");
        fieldMap.put("pointName","点位名称");
        fieldMap.put("devCode","点位代码");

        //导出信息
        new ExcelUtil().export(excelName,pointlist,fieldMap,response);
    }


}
